import chardet
from pathlib import Path


def detect_encoding(file_path):
    """检测文件编码。"""
    with open(file_path, 'rb') as f:
        result = chardet.detect_all(f.read())
        encodings = sorted(result, key=lambda x: x['confidence'], reverse=True)  # 按置信度排序
        return encodings[0]['encoding']


def list_files_with_encoding(directory):
    """遍历指定目录下的所有文件"""
    directory_path = Path(directory)
    for file in directory_path.glob("**/*.txt"):  # 遍历指定目录下的所有文件
        encoding = detect_encoding(file)  # 检测文件的编码
        print(f"文件名: {file.name}, 编码: {encoding}")


directory_to_search = r"D:\SoftWare\SmartGit\git\usr\share\gnupg"
list_files_with_encoding(directory_to_search)
